import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ChargeService} from '../../service/charge.service';
import {SharedModule} from '../shared.module';
import {ChargeForm} from '../../types/req/ChargeForm';
import {MODAL_WIDTH} from '../../const'
import {BuildingSelectorComponent} from '../building/building-selector.component';
import {RoomSelectorComponent} from '../room/room-selector.component';

@Component({
  selector: 'charge-add',
  imports: [
    BuildingSelectorComponent,
    RoomSelectorComponent,
    SharedModule
  ],
  templateUrl: './charge-add.component.html',
  standalone: true
})
export class ChargeAddComponent implements OnInit {
  chargeToSave:ChargeForm = {};
  chargeForm!: FormGroup;
  isVisible: boolean = false
  saveLoading: boolean = false
  title: string = '新增收费信息'
  modalWidth: string = MODAL_WIDTH

  @ViewChild(BuildingSelectorComponent, { static: false }) buildingSelectorComponent!: BuildingSelectorComponent;
  @ViewChild(RoomSelectorComponent, { static: false }) roomSelectorComponent!: RoomSelectorComponent;

  @Output() addedEvent = new EventEmitter<boolean>();

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private chargeService: ChargeService
  ) {}

  ngOnInit(): void {
    this.chargeForm = this.fb.group({
      buildingId: [0],
      buildingName: ['', [Validators.required]],
      roomId: [0],
      roomNumber: ['', [Validators.required]],
      chargeType: [undefined, [Validators.required]],
      billingCycle: [''],
      billingStartDate: [''],
      billingEndDate: [''],
      amount: [0],
      lateFee: [0],
      dueDate: [''],
      paymentDate: [''],
      paymentStatus: [undefined],
    })
  }

  onSave() {
    try {
      this.saveLoading = true
      for (const i in this.chargeForm.controls) {
        this.chargeForm.controls[i].markAsDirty();
        this.chargeForm.controls[i].updateValueAndValidity();
      }
      if (!this.chargeForm.valid) {
        this.saveLoading = false
        return
      }
      this.chargeService.save(Object.assign(this.chargeToSave, this.chargeForm.value)).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          this.message.success("保存成功")
          this.onBack(true)
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onReset() {
    this.title = '新增收费信息'.slice()
    this.chargeForm.reset()
  }

  onBack(addedFlag=false) {
    this.isVisible = false
    this.addedEvent.emit(addedFlag);
  }

  display(id: number) {
    this.isVisible = true
    if (id) {
      this.title = '修改收费信息'
      this.saveLoading = true
      this.chargeService.findById(id).subscribe({
        next: (resp) => {
          if (resp && resp.code === 1 && resp.data) {
            this.chargeToSave = resp.data
            this.chargeForm.patchValue(this.chargeToSave);
          }
        },
        complete: () => {
          this.saveLoading = false
        }
      })
    } else {
      this.onReset()
    }
  }

  findBuilding() {
    this.buildingSelectorComponent.display()
  }

  handleBuildingSelectedEvent(selectedBuilding: { buildingId?: number; buildingName?: string; }) {
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      this.chargeForm.patchValue(selectedBuilding);
    }
  }

  findRoom() {
    this.roomSelectorComponent.display()
  }

  handleRoomSelectedEvent(selectedRoom: { roomId?: number; roomNumber?: string; }) {
    if (selectedRoom && 'roomId' in selectedRoom) {
      this.chargeForm.patchValue(selectedRoom);
    }
  }
}
